package com.apply.repository.spec;

import com.apply.entity.SysUser;
import com.apply.entity.SysUser_;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @author tianp
 */
public class UserRepositorySpec {
    /**
     * 根据姓名，手机号 查询 性别
     *
     * @param relName
     * @param phoneNum
     * @param sex
     * @return
     */
    public static Specification<SysUser> getSpec(final String relName, final String phoneNum, final String sex) {
        return new Specification<SysUser>() {
            @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate p1 = null;
                if (relName != null) {
                    Predicate p2 = cb.like(root.get(SysUser_.realname), "%" + relName + "%");
                    if (p1 != null) {
                        p1 = cb.and(p1, p2);
                    } else {
                        p1 = p2;
                    }
                }
                if (phoneNum != null) {
                    Predicate p2 = cb.equal(root.get(SysUser_.username), "%" + phoneNum + "%");
                    if (p1 != null) {
                        p1 = cb.and(p1, p2);
                    } else {
                        p1 = p2;
                    }
                }
                if (sex != null) {
                    Predicate p2 = cb.equal(root.get(SysUser_.sex), sex);
                    if (p1 != null) {
                        p1 = cb.and(p1, p2);
                    } else {
                        p1 = p2;
                    }
                }
                Predicate p2 = cb.equal(root.get(SysUser_.roleId), 1);
                if (p1 != null) {
                    p1 = cb.and(p1, p2);
                } else {
                    p1 = p2;
                }
                return p1;
            }
        };
    }
}
